import React, { memo, useState, useEffect } from 'react';
import { useIntersectionObserver } from '../hooks/useIntersectionObserver';

interface LazyLoadWrapperProps {
  children: React.ReactNode;
  placeholder?: React.ReactNode;
  height?: number;
  once?: boolean;
}

export const LazyLoadWrapper: React.FC<LazyLoadWrapperProps> = memo(({
  children,
  placeholder = <div style={{ height: '200px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: '#999' }}>加载中...</div>,
  height = 200,
  once = true
}) => {
  const [shouldRender, setShouldRender] = useState(false);
  const { elementRef, isIntersecting, hasIntersected } = useIntersectionObserver({
    threshold: 0.1,
    rootMargin: '100px'
  });

  useEffect(() => {
    if (isIntersecting || (once && hasIntersected)) {
      setShouldRender(true);
    } else if (!once && !isIntersecting) {
      setShouldRender(false);
    }
  }, [isIntersecting, hasIntersected, once]);

  return (
    <div ref={elementRef} style={{ minHeight: height }}>
      {shouldRender ? children : placeholder}
    </div>
  );
});

LazyLoadWrapper.displayName = 'LazyLoadWrapper';

export default LazyLoadWrapper;